package com.flyme.common.security.util;

import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.flyme.common.security.util.SecurityUtils.USER_SESSION_LOGIN_KEY;
import static com.flyme.common.security.util.SecurityUtils.USER_SESSION_USER_INFO_KEY;

/**
 * Created by xinxingegeya on 2017/5/25.
 */
public class SecurityContextFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (request.getSession().getAttribute(USER_SESSION_LOGIN_KEY) != null && (Boolean) request.getSession().getAttribute(USER_SESSION_LOGIN_KEY)) {
            SecurityUtils.bindSubject(request.getSession().getAttribute(USER_SESSION_USER_INFO_KEY));
        }
        try {
            filterChain.doFilter(request, response);
        } finally {
            Object subject = SecurityUtils.getSubject();
            if (subject != null) {
                SecurityUtils.removeSubject();
            }
        }
    }
}
